package com.yejiali.backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yejiali.backend.entity.Messages;
import com.yejiali.backend.entity.dto.MessageDTO;
import com.yejiali.backend.entity.vo.SendMsPersonsVO;
import com.yejiali.backend.entity.vo.UnReadMessageCountVO;
import com.yejiali.backend.mapper.MessagesMapper;
import com.yejiali.backend.mapper.UsersMapper;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.MessagesService;
import com.yejiali.backend.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息表(Messages)表服务实现类
 *
 * @author yejiali
 * @since 2025-08-18 17:10:53
 */
@Service
public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, Messages> implements MessagesService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private MessagesMapper messagesMapper;

    @Autowired
    private RedisUtil redisUtil;



    /**
     * 标记未读消息条数(所有类型消息)
     */
    @Override
    public Response<UnReadMessageCountVO> unreadCount(Long userId) {
        Map<Object, Object> unReadCount = redisUtil.hmget("user:unread:" + userId);
        UnReadMessageCountVO unReadMessageCountVO = new UnReadMessageCountVO();
        Object replyMessageObj = unReadCount.get("replyMessage");
        unReadMessageCountVO.setReplyMessage(replyMessageObj != null ? (Integer) replyMessageObj : 0);
        Object likeMessageObj = unReadCount.get("likeMessage");
        unReadMessageCountVO.setLikeMessage(likeMessageObj != null ? (Integer) likeMessageObj : 0);
        Object atMeMessageObj = unReadCount.get("atMeMessage");
        unReadMessageCountVO.setAtMeMessage(atMeMessageObj != null ? (Integer) atMeMessageObj : 0);
        Map<Object, Object> unReadMessage = redisUtil.hmget("unreadCount:" + userId);
        Integer total = 0;
        for (Object key : unReadMessage.keySet()) {
            Integer value = (Integer) unReadMessage.get(key);
            total += value;
        }
        unReadMessageCountVO.setMyMessage(total);
        return Response.success(unReadMessageCountVO);
    }


    /**
     * 查询给我发消息的人
     * @param userId
     * @return
     * 查询他的id,头像和最近一条给我发的消息
     */
    @Override
    public Response<?> sendMyMessagePerson(Long userId) {
        //id是否有效
        if (userId == null || usersMapper.selectById(userId) == null) {
            throw new IllegalArgumentException("参数错误");
        }
        //查询
        List<SendMsPersonsVO> sendMsPersonsVOS = messagesMapper.selectSendPersons(userId);

        //拉去消息未读数
        Map<String, Object> map = redisUtil.hmgetMap("unreadCount:" + userId);
        // 将未读消息数设置到 SendMsPersonsVO 对象中
        for (SendMsPersonsVO vo : sendMsPersonsVOS) {
            String key = String.valueOf(vo.getUserId());
            if (map.containsKey(key)) {
                Integer value = (Integer) map.get(key);
                vo.setUnreadCount(value);
            } else {
                vo.setUnreadCount(0);
            }
        }
        return Response.success(sendMsPersonsVOS);
    }

    /**
     * 查询消息
     * @param myId
     * @param toId
     * @return
     */
    @Override
    public Response<?> getMessages(Long myId, Long toId) {
        QueryWrapper<Messages> wrapper = new QueryWrapper<>();
        wrapper.eq("receiver_id",myId)
                .eq("sender_id",toId)
                .or()
                .eq("receiver_id",toId)
                .eq("sender_id",myId)
                .orderByDesc("send_time");
        //查询
        List<Messages> messages = list(wrapper);
        //转换
        List<MessageDTO> messageDTOS = BeanUtil.copyToList(messages, MessageDTO.class);
        return Response.success(messageDTOS);
    }

    /**
     * 标记消息为已读
     * @param userId
     */
    @Override
    public Response<String> markMessageAsRead(Long userId, Long sender) {
        //检查参数
        if (userId == null || usersMapper.selectById(userId) == null) {
            throw new IllegalArgumentException("参数错误");
        }
        //更新redis
        redisUtil.hdel("unreadCount:" + userId, String.valueOf(sender));
        return Response.success("标记成功");
    }
    /**
     * 保存消息
     * @param toUserId
     * @param fromUserId
     * @param message
     */
    public void saveMessage(Long toUserId, Long fromUserId, String message) {
        //检查参数
        if (toUserId == null || fromUserId == null || message == null) {
            throw new IllegalArgumentException("参数错误");
        }
        //创建消息对象
        Messages messages = new Messages();
        messages.setReceiverId(toUserId);
        messages.setSenderId(fromUserId);
        messages.setContent(message);
        //保存
        this.save(messages);
    }

    /**
     * 标记未读消息条数
     * @param receiverId
     * @param senderId
     * @return
     */
    @Override
    public Response<String> markUnreadCount(Long receiverId, Long senderId) {
        redisUtil.hincr("unreadCount:" + receiverId, String.valueOf(senderId), 1);
        return Response.success("标记成功");
    }


}


